import json
from croniter import croniter
from flask import render_template, request
from aide.UserAide import User
from aide.TasksAide import TasksAide
from aide.TasksGroupAide import TasksGroupAide
from aide.EscResourceAide import EscResourceAide
from conf.menu import menu
from conf.db import get_db


class AdminController:
    def __init__(self):
        self.page_title = None
        self.nav = menu
        self.db = get_db()

    def index(self):
        self.page_title = '首页'
        data = [
            {'label': '总任务数', 'value': self.db.count('tasks'), 'icon': 'mdi mdi-access-point'},
            {'label': '执行中任务数', 'value': self.db.count('tasks', 'status = 1'), 'icon': 'mdi mdi-access-point-network'},
            {'label': '停止中任务数', 'value': self.db.count('tasks', 'status != 1'), 'icon': 'mdi mdi-av-timer'},
            {'label': '执行日志数', 'value': self.db.count('tasks_log'), 'icon': 'mdi mdi-autorenew'},
            {'label': '执行成功数', 'value': self.db.count('tasks_log', 'status = 1'), 'icon': 'mdi mdi-basket'},
            {'label': '执行失败数', 'value': self.db.count('tasks_log', 'status != 1'), 'icon': 'mdi mdi-biohazard'},
            {'label': '执行资源数', 'value': self.db.count('esc_resource'), 'icon': 'mdi mdi-blur-radial'},
            {'label': '任务分组数', 'value': self.db.count('tasks_group'), 'icon': 'mdi mdi-book-multiple'},
        ]
        return render_template('admin/index.html', this=self, data=data)

    # 任务列表
    def tasks_list(self):
        self.page_title = '任务列表'
        cfg = TasksAide.cfg
        condition = '1'
        if request.args.get('group_id'):
            condition += ' AND group_id = {}'.format(request.args.get('group_id'))
        data = self.db.findAll('tasks', condition)
        TasksAide.tasks_list_fmt(cfg, data)
        # 分组标签
        task_groups = self.db.findAll('tasks_group', '1')
        for one in task_groups:
            one['task_cnt'] = self.db.count('tasks', 'group_id = {}'.format(one['id']))
        return render_template('admin/tasks_list.html', this=self, cfg=cfg, data=data, task_groups=task_groups)

    # 任务执行日志列表
    def tasks_log_list(self):
        self.page_title = '日志列表'
        _id = request.args.get('id', 0)
        cfg = TasksAide.log_list_cfg()
        # field = "*,strftime('%Y-%m-%d %H:%M:%S',created_at,'localtime') as ct"
        field = "*,strftime('%Y-%m-%d %H:%M',created_at,'localtime') as ct"
        data = self.db.findAll('tasks_log', 'tid = {}'.format(_id), field, order='created_at DESC', limit=50)
        TasksAide.tasks_log_list_fmt(cfg, data)
        return render_template('admin/tasks_log_list.html', this=self, cfg=cfg, data=data)

    # 任务分组列表
    def tasks_group_list(self):
        self.page_title = '任务列表'
        cfg = TasksGroupAide.cfg
        data = self.db.findAll('tasks_group', '1')
        return render_template('admin/tasks_group_list.html', this=self, cfg=cfg, data=data)

    # 服务器列表
    def resource_list(self):
        self.page_title = '资源列表'
        cfg = EscResourceAide.cfg
        data = self.db.findAll('esc_resource', '1')
        EscResourceAide.resource_list_fmt(cfg, data)
        return render_template('admin/resource_list.html', this=self, cfg=cfg, data=data)

    # 用户列表
    def users_list(self):
        self.page_title = '用户列表'
        cfg = User.cfg
        data = self.db.findAll('users', '1')
        return render_template('admin/users_list.html', this=self, cfg=cfg, data=data)

    # 编辑任务
    def edit_task(self):
        self.page_title = '编辑任务'
        _id = request.args.get('id', 0)
        model = self.db.find('tasks', 'id = {}'.format(_id))
        if not model:
            model = {}
        if request.form:
            cfg = TasksAide.cfg
            sql_data = request.form
            if 1 == model.get('status'):
                return json.dumps({'error': 1, 'message': '修改失败，任务正在执行中！'})
            if croniter.is_valid(sql_data.get('crontab_expression', '')) is False:
                return json.dumps({'error': 2, 'message': '时间表达示不合法，请核对！'})
            for i in cfg:
                if i['required'] and not sql_data.get(i['field']):
                    return json.dumps({'error': 1, 'message': '{}必填'.format(i['label'])})
            if model:
                self.db.update('tasks', sql_data, 'id = {}'.format(_id))
            else:
                self.db.insert('tasks', sql_data)
            return json.dumps({'error': 0, 'message': '操作成功'})
        cfg = TasksAide.edit_cfg()
        return render_template('admin/edit.html', this=self, cfg=cfg, model=model)

    # 编辑任务分组
    def edit_tasks_group(self):
        self.page_title = '编辑分组'
        _id = request.args.get('id', 0)
        model = self.db.find('tasks_group', 'id = {}'.format(_id))
        if not model:
            model = {}
        cfg = TasksGroupAide.edit_cfg()
        if request.form:
            sql_data = request.form
            for i in cfg:
                if i['required'] and not sql_data.get(i['field']):
                    return json.dumps({'error': 1, 'message': '{}必填'.format(i['label'])})
            if model:
                self.db.update('tasks_group', sql_data, 'id = {}'.format(_id))
            else:
                self.db.insert('tasks_group', sql_data)
            return json.dumps({'error': 0, 'message': '操作成功'})
        for i in cfg:
            i['type'] = 'text'
        return render_template('admin/edit.html', this=self, cfg=cfg, model=model)

    # 编辑服务器
    def edit_resource(self):
        self.page_title = '资源添加'
        _id = request.args.get('id', 0)
        model = self.db.find('esc_resource', 'id = {}'.format(_id))
        if not model:
            model = {}
        if request.form:
            cfg = EscResourceAide.cfg
            sql_data = request.form
            for i in cfg:
                if i['required'] and not sql_data.get(i['field']):
                    return json.dumps({'error': 1, 'message': '{}必填'.format(i['label'])})
            if model:
                self.db.update('esc_resource', sql_data, 'id = {}'.format(_id))
            else:
                self.db.insert('esc_resource', sql_data)
            return json.dumps({'error': 0, 'message': '操作成功'})
        cfg = EscResourceAide.edit_cfg()
        return render_template('admin/edit.html', this=self, cfg=cfg, model=model)

    # 编辑用户
    def edit_user(self):
        self.page_title = '编辑用户'
        _id = request.args.get('id', 0)
        model = self.db.find('users', 'id = {}'.format(_id))
        if not model:
            model = {}
        cfg = User.edit_cfg()
        if request.form:
            sql_data = request.form
            for i in cfg:
                if i['required'] and not sql_data.get(i['field']):
                    return json.dumps({'error': 1, 'message': '{}必填'.format(i['label'])})
            if model:
                self.db.update('users', sql_data, 'id = {}'.format(_id))
            else:
                self.db.insert('users', sql_data)
            return json.dumps({'error': 0, 'message': '操作成功'})
        return render_template('admin/edit.html', this=self, cfg=cfg, model=model)

    # 日志详情
    def show_log_detail(self):
        _id = request.args.get('id', 0)
        if _id:
            data = self.db.find('tasks_log', 'id = {}'.format(_id))
        task_id = request.args.get('task_id', 0)
        if task_id:
            data = self.db.find('tasks_log', 'tid = {}'.format(task_id), order='created_at DESC')
        result = data['result'][1:-1].replace(r'\n', '<br/>')
        return json.dumps({'error': 0, 'message': '操作成功', 'data': result})

    # 删除服务器
    def delete_ecs(self):
        _id = request.args.get('id', 0)
        self.db.delete('esc_resource', 'id = {}'.format(_id))
        return json.dumps({'error': 0, 'message': '操作成功'})

    # 删除任务
    def delete_task(self):
        _id = request.args.get('id', 0)
        self.db.delete('tasks', 'id = {}'.format(_id))
        return json.dumps({'error': 0, 'message': '操作成功'})

    # 删除任务
    def delete_group(self):
        _id = request.args.get('id', 0)
        self.db.delete('tasks_group', 'id = {}'.format(_id))
        return json.dumps({'error': 0, 'message': '操作成功'})
